package org.quarenden.demo.util;

import java.net.NetworkInterface;
import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;
import java.security.SecureRandom;
import java.util.Enumeration;

/**
 * @author liboyi
 * 按照相应规则获取机器编码
 */
public class MachineIdentifierUtil {
    private static final int LOW_ORDER_THREE_BYTES = 0x0ff0;

    public static int createMachineIdentifier() {
        // build a 2-byte machine piece based on NICs info
        int machinePiece;
        try {
            StringBuilder sb = new StringBuilder();
            Enumeration<NetworkInterface> e = NetworkInterface.getNetworkInterfaces();
            while (e.hasMoreElements()) {
                NetworkInterface ni = e.nextElement();
                sb.append(ni.toString());
                //System.out.println(ni.getInetAddresses());
                byte[] mac = ni.getHardwareAddress();
                if (mac != null) {
                    //System.out.println(parseByte(mac[0]));
                    ByteBuffer bb = ByteBuffer.wrap(mac);
                    try {
                        sb.append(bb.getChar());
                        sb.append(bb.getChar());
                        sb.append(bb.getChar());
                    } catch (BufferUnderflowException shortHardwareAddressException) { //NOPMD
                        // mac with less than 6 bytes. continue
                    }
                }
            }
            machinePiece = sb.toString().hashCode();
            //System.out.println(machinePiece);
            //System.out.println("ManagementFactory:"+ManagementFactory.getRuntimeMXBean().getName().hashCode());
            //System.out.println(String.valueOf(LOW_ORDER_THREE_BYTES));
        } catch (Throwable t) {
            // exception sometimes happens with IBM JVM, use random
            machinePiece = (new SecureRandom().nextInt());
            System.out.println("Failed to get machine identifier from network interface, using random number instead");
        }
        machinePiece = machinePiece & LOW_ORDER_THREE_BYTES;
        return machinePiece;
    }

    private static String parseByte(byte b) {
        int intValue = 0;
        if (b >= 0) {
            intValue = b;
        } else {
            intValue = 256 + b;
        }
        return Integer.toHexString(intValue);
    }
}
